package com.dongdong.service.impl;

import com.dongdong.api.CartApi;
import com.dongdong.api.ItemApi;
import com.dongdong.api.UserApi;
import com.dongdong.mapper.TbOrderItemMapper;
import com.dongdong.mapper.TbOrderMapper;
import com.dongdong.model.TbAddress;
import com.dongdong.model.TbOrder;
import com.dongdong.model.TbOrderExample;
import com.dongdong.model.TbOrderItem;
import com.dongdong.service.OrderService;
import com.dongdong.utils.IdWorker;
import com.dongdong.utils.JwtUtil;
import com.dongdong.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private UserApi userApi;
    @Autowired
    private CartApi cartApi;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ItemApi itemApi;

    @Override
    @Transactional
    @GlobalTransactional
    public PayVO addOrderAndOrderItem(String accessToken, Long addrId, String paymentType) {
        String userId = jwtUtil.parseJwt(accessToken).getId();

//        调用获取当前用户的地址信息
        TbAddress address = userApi.getAddressById(addrId);
//        调用获取当前用户的redis购物车列表
        List<CartVO> cartList = cartApi.getCartList(accessToken);

        String outTradeNo = null;
        BigDecimal payMoney = new BigDecimal(0);
        StringBuilder subject = new StringBuilder();

        ArrayList<ItemVO> itemVOS = new ArrayList<>();
        List<TbOrder> orderList = new ArrayList<>();
        List<TbOrderItem> orderItemList = new ArrayList<>();
        for (CartVO cartVO : cartList) {
            TbOrder order = new TbOrder();
            order.setOrderId(idWorker.nextId());
            order.setPaymentType(paymentType);
            order.setStatus("1");
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setUserId(address.getUserId());
            order.setReceiverAreaName(address.getAddress());
            order.setReceiverMobile(address.getMobile());
            order.setReceiver(address.getContact());
            order.setSellerId(cartVO.getSeller());
            order.setOutTradeNo(idWorker.nextId()+"");

            outTradeNo = order.getOutTradeNo();

            BigDecimal money = new BigDecimal(0);
            List<CartDetailVO> detailList = cartVO.getDetailVOS();
            for (CartDetailVO detailVO : detailList) {
                TbOrderItem orderItem = new TbOrderItem();
                orderItem.setId(idWorker.nextId());
                orderItem.setItemId(detailVO.getItemId());
                orderItem.setGoodsId(detailVO.getGoodsId());
                orderItem.setOrderId(order.getOrderId());
                orderItem.setTitle(detailVO.getTitle());
                orderItem.setPrice(detailVO.getPrice());
                orderItem.setNum(detailVO.getNum());
                orderItem.setTotalFee(detailVO.getTotalFee());
                orderItem.setPicPath(detailVO.getPicPath());
                orderItem.setSellerId(cartVO.getSeller());

                orderItem.setOutTradeNo(order.getOutTradeNo());

                ItemVO itemVO = new ItemVO();
                itemVO.setId(orderItem.getItemId());
                itemVO.setStockCount(orderItem.getNum());
                itemVOS.add(itemVO);

                orderItemList.add(orderItem);

                money = money.add(detailVO.getTotalFee());
                payMoney=money;
                subject.append(detailVO.getTitle());
            }

            order.setPayment(money);
            orderList.add(order);
        }


//        扣减库存
        itemApi.subCount(itemVOS);
//        增加order和orderItem
        orderMapper.insertBatch(orderList);
        orderItemMapper.insertBatch(orderItemList);

//        删除缓存
//        redisTemplate.delete("cart"+userId);//删大key
        redisTemplate.boundHashOps("cart").delete(userId);//删小key

//        组装调用支付接口需要的参数
        PayVO payVO = new PayVO();
//        1.订单编号
        payVO.setOutTradeNo(outTradeNo);
//        2.交易金额
        payVO.setTotalAmount(payMoney.toString());
//        3.标题
        payVO.setSubject(subject.toString());
        return payVO;
    }

    @Override
    public void updatePayOrder(TbOrder order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public void updatePayOrderItem(TbOrderItem item) {
        orderItemMapper.updateByPrimaryKeySelective(item);
    }

    @Override
    public TbOrder selectByOutTradeNo(String outTradeNo) {

        return orderMapper.selectByOutTradeNo(outTradeNo);
    }

    @Override
    public TbOrderItem selectByItemOutTradeNo(String outTradeNo) {

        return orderItemMapper.selectByItemOutTradeNo(outTradeNo);
    }
}
